/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dbclasses;

import classes.User;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.JOptionPane;

/**
 * Class with the sole purpose of verifying the user logging on
 * @author keaneb1
 */
public class Dologin {
    
    private static Connection conn = null;
    private static Statement st = null;
    
    /**
     * Method to check the credentials with the user table in the database
     * @param userName the username to be verified
     * @param password the password for the username
     * @return the user if exists in the database
     */
    public static User login(String userName, String password) {
        User user = null;
        //first get a new connection from the Dbconnector class
        conn = Dbconnector.getConnected();
        if(conn!=null){
            try{
                //query the database and check if the username / password combindation exists
                st = conn.createStatement();
                
                ResultSet rs = st.executeQuery("SELECT * from user WHERE username='" + userName + "' and"
                        + " password='" + password + "'");
                
                if (rs.first()) {
                    //initialise a new user object if one is returned
                    user = new User(rs.getString("username"),rs.getString("password"));
                }
                //close the database connection
                conn.close();
            
            } catch (SQLException ex) {
                //tell the client which method call errored out and what was the message
                JOptionPane.showMessageDialog(null, "Problem " +ex.getSQLState());
            }
        }
        return user;
    }
}
